package Prac;

public class P11_23 {
    public ListNode removeElements1(ListNode head, int val) {
        if (head == null) {
            return null;
        }
        while (head != null && head.val == val) {
            ListNode next = head.next;
            head.next = null;
            head = next;
        }
        if (head == null) {
            return null;
        }
        ListNode prev = head;
        while (prev.next != null) {
            ListNode cur = prev.next;
            if (cur.val == val) {
                prev.next = cur.next;
                cur.next = null;
            } else {
                prev = prev.next;
            }
        }
        return head;
    }

    /**递归法实现
     * 传入一个以head为头节点的链表,和一个val值,就可以删除所有val值为val的节点
     * @param head
     * @param val
     * @return
     */
    public ListNode removeElements(ListNode head, int val) {
        if(head==null){//为空就return
            return null;
        }
        //删除以head.next为头节点的链表中所有val值等于val的节点
        head.next =removeElements(head.next,val);
        return head.val==val?head.next:head;//如果head.val!=val,则return已经处理好的head.next为头的子节点;如果head.val!=val,则直接返回head
    }
}
